package com.example.nebula.config;

import com.vesoft.nebula.client.graph.SessionPool;
import com.vesoft.nebula.client.graph.SessionPoolConfig;
import com.vesoft.nebula.client.graph.data.HostAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fulin
 * 配置全局唯一session链接
 **/
@Component
public class NebulaSession {
    @Autowired
    NebulaGraphProperties nebulaGraphProperties;

    @Bean
    public SessionPool sessionPool() throws Exception {
        List<HostAddress> addresses = getGraphHostPort(nebulaGraphProperties.getHostAddresses().get(0));
        SessionPoolConfig sessionPoolConfig =
                new SessionPoolConfig(addresses, "flceshi", nebulaGraphProperties.getUserName(), nebulaGraphProperties.getPassword())
                        .setMaxSessionSize(nebulaGraphProperties.getMaxConnSize())
                        .setMinSessionSize(nebulaGraphProperties.getMinConnsSize())
                        .setRetryConnectTimes(3)
                        .setWaitTime(nebulaGraphProperties.getWaitTime())
                        .setRetryTimes(3)
                        .setIntervalTime(100);
        SessionPool sessionPool = new SessionPool(sessionPoolConfig);
        return sessionPool;
    }

    private List<HostAddress> getGraphHostPort(String hostAndPort) {
        String[] split = hostAndPort.split(",");
        return Arrays.stream(split).map(item -> {
            String[] splitList = item.split(":");
            return new HostAddress(splitList[0], Integer.parseInt(splitList[1]));
        }).collect(Collectors.toList());
    }


}
